import React from "react";
import BaseComponent from "../../../redare/components/BaseComponent";
import {Input, Spin, Tree} from "antd";
import DictionaryPresenter from "../../../.gen/presenter/DictionaryPresenter";

export default class DepartmentTree extends BaseComponent {

    // 属性默认展开的层数
    _initExpandedKeys_tier=2;

    constructor(props) {
        super(props);
        this.state = {
            treeData: [],
            expandedKeys: [],
            autoExpandParent: true,
            searchValue: ''
        };
        this.presenter = new DictionaryPresenter(this)
    }

    componentDidMount() {
        this._loadDeptTreeData()
    }

    _loadDeptTreeData() {
        this.presenter.findDingDepartmentList(
            {},
            {},
            (result) => {
                let {data} = result;
                let treeData = [];
                data.map(record => {
                    treeData.push({
                        id: record.id + "",
                        key: record.id + "",
                        departmentParentId: record.departmentParentId,
                        departmentId: record.departmentId,
                        title: record.departmentName,
                        isLeaf: record.leaf,
                    });
                });
                let changeTreeData = this.changeReturnedDataToTreeFormat(treeData);
                this.dataList = treeData;
                this.treeData = changeTreeData;

                // 默认展开第一层
                let _expandedKeys = [];
                let _initExpandedKeys_count = 1 ;

                let _initExpandedKeys =  (data)=>{
                    _initExpandedKeys_count++;
                    if( data && data.length > 0 ){
                        data.map((item)=>{
                            if( _initExpandedKeys_count <= this._initExpandedKeys_tier){
                                _initExpandedKeys(item.children);
                            }
                            _expandedKeys.push(item.key+"")
                        });
                    }
                }

                _initExpandedKeys(changeTreeData);

                this.setState({
                    treeData: changeTreeData,
                    loading: false,
                    expandedKeys: _expandedKeys,
                    autoExpandParent: false
                });
            }
        )
    }

    changeReturnedDataToTreeFormat(data) {
        let parentArr = [];
        data.map(item => {
            if (item.departmentParentId == 0) {
                parentArr.push(item)
            }
        });
        return this.generateChildrenData(parentArr, data)
    }

    generateChildrenData(parentArr, data) {
        parentArr.map(item => {
            item.children = data.filter(record => item.departmentId === record.departmentParentId);
            if (item.children.length > 0) {
                this.generateChildrenData(item.children, data)
            }
        });
        return parentArr
    }

    onChange(e) {
        const {value} = e.target;
        let expandedKeys = this.state.expandedKeys || [];
        if (value && value.length > 0) {
            expandedKeys = this.dataList
                .map(item => {
                    if (item.title.indexOf(value) > -1) {
                        return this.getParentKey(item.key, this.treeData);
                    }
                    return null;
                })
                .filter((item, i, self) => item && self.indexOf(item) === i)
        } else {
            expandedKeys = this.onExpandExpandedKeys;
        }
        this.setState({
            expandedKeys,
            searchValue: value,
            autoExpandParent: true,
        });
    }

    getParentKey = (key, tree) => {
        let parentKey;
        for (let i = 0; i < tree.length; i++) {
            const node = tree[i];
            if (node.children) {
                if (node.children.some(item => item.key === key)) {
                    parentKey = node.key;
                } else if (this.getParentKey(key, node.children)) {
                    parentKey = this.getParentKey(key, node.children);
                }
            }
        }
        return parentKey;
    };

    onExpand(expandedKeys) {
        this.onExpandExpandedKeys = expandedKeys;
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    }

    onSelect(key, e) {
        this.sendEvent('on_department_tree_select', e.node.props.dataRef)
    }

    renderTreeNodes = (data) => {
        let {searchValue} = this.state;
        return data.map(item => {
            const index = item.title.indexOf(searchValue);
            const beforeStr = item.title.substr(0, index);
            const afterStr = item.title.substr(index + searchValue.length);
            const title =
                index > -1 ? (
                    <span>
              {beforeStr}
                        <span style={{color: '#f50'}}>{searchValue}</span>
                        {afterStr}
          </span>
                ) : (
                    <span>{item.title}</span>
                );
            if (item.children) {
                return (
                    <Tree.TreeNode title={title} key={item.key} dataRef={item}>
                        {this.renderTreeNodes(item.children)}
                    </Tree.TreeNode>
                );
            }
            return <Tree.TreeNode key={item.key} {...item} title={title} dataRef={item}/>;
        });
    };

    render() {
        let {treeData} = this.state;
        return (
            <>
                <Input.Search style={{marginBottom: 8}} placeholder="搜索" onChange={this.onChange.bind(this)}/>
                <Spin spinning={this.state.loading}
                      tip={'加载中...'}
                      wrapperClassName="full-screen-loading"
                      className={"classify-spin-position"}
                >
                    <div style={{height: 'calc(100vh - 300px)', overflow: 'auto', marginLeft: '-5px'}}>
                        <Tree
                            style={{color: 'rgba(0,0,0,0.65)'}}
                            showLine={{showLeafIcon:false}}
                            onExpand={this.onExpand.bind(this)}
                            onSelect={this.onSelect.bind(this)}
                            expandedKeys={this.state.expandedKeys}
                            autoExpandParent={this.state.autoExpandParent}
                        >
                            {this.renderTreeNodes(treeData)}
                        </Tree>
                    </div>
                </Spin>
            </>
        );
    }

}